<?php

namespace app\api\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Category;
use app\admin\model\product\Listo;
use app\admin\model\product\Lists;
use app\admin\model\product\Order;
use app\admin\model\product\Sku;
use app\admin\model\product\Value;
use app\admin\model\user\Finance;
use app\common\api\controller\Relation;
use app\common\model\Member;
use app\common\model\MemberFinance;
use think\Db;
use think\Request;
use app\common\controller\Api;
use think\Validate;

class Tforder extends Api
{
    protected static $model = null;
    protected $noNeedRight = '*';

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        self::$model = new \app\admin\model\tf\Order();
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $list = self::$model
            ->where('user_id', $this->auth->id)
            ->order('id desc')
            ->select();

        if ($list) {
            foreach ($list as $val) {
                $val->createtime = date('Y-m-d H:i:s', $val->createtime);
            }
        }

        $this->success('订单列表为', $list);
    }

    /**
     * 创建兑换订单
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create()
    {
        if (!request()->isPost()) {
            $this->error('非法操作！');
        }
        $date = date('w', time());
        if (!in_array($date, ['6', '0'])) {
            $this->error('非周六日不可兑换！');
        }

        $user_id = $this->auth->id;
        $monday = strtotime(date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600)));
        $row = self::$model
            ->where('status', '>=', 0)
            ->where('createtime', '>=', $monday)
            ->where('user_id', $user_id)
            ->find();
        if ($row) {
            $this->error('本周已兑换过！');
        }

        $moneytype = input('moneytype');
        if (!in_array($moneytype, [1, 2, 4])) {
            $this->error('币种错误！');
        }

        if ($moneytype != 1) {
            $money = input('money');
            if (!$money || $money <= 0) {
                $this->error('必须输入正确兑换金额！');
            }
        }

        $type = input('type');
        if (!in_array($type, [1, 2, 3])) {
            $this->error('请选择正确兑换类型！');
        }

        $finance = Finance::where('user_id', $user_id)->find();
        if ($moneytype == 1) {
            if ($finance->hasscore <= 0) {
                $this->error('不可兑换');
            }
            $money = $finance->hasscore;
        } elseif ($moneytype == 2) {
            $tf_hasmoney_multi = config('site.tf_hasmoney_multi');
            if ($money < $tf_hasmoney_multi) {
                $this->error('兑换最低额度为' . $tf_hasmoney_multi . '！');
            }
            if ($money % $tf_hasmoney_multi) {
                $this->error('额度必须为' . $tf_hasmoney_multi . '的整数倍！');
            }
        }

        if ($moneytype == 4 && $type != 3) {
            $this->error('币种和兑换类型不匹配！');
        }

        switch ($moneytype) {
            case 1:
                $field = 'hasscore';
                break;
            case 2:
                $field = 'hasmoney';
                break;
            case 4:
                $field = 'hasstatic';
                break;
        }
        if ($money > $finance->$field) {
            $this->error('账户余额不足，无法兑换！');
        }

        Db::startTrans();
        try {
            $finance->$field -= $money;
            $finance->save();

            $data = [
                'user_id' => $user_id,
                'moneytype' => $moneytype,
                'type' => $type,
                'money' => $money,
                'status' => 0
            ];
            $odata = self::$model->create($data);
            $id = $odata->id;

            $orderNum = create_order($user_id);
            $mdata1 = [
                'order_num' => $orderNum,
                'record_type' => 0,
                'change_type' => 6,
                'moneytype' => $moneytype,
                'money' => $money,
                'hasmoney' => $finance->$field,
//                'remark' => $tag,
                'user_id' => $user_id,
                'targetuserid' => $user_id
            ];
            Change::create($mdata1);

            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('兑换订单申请成功！');
    }
}